var nodemailer = require("nodemailer");
var userModel = require("../models/user.model");
var nodeRSA = require("node-rsa");
var config = require("../config.lib");

async function sendMail(req, res, next, doc){
    let url = "http://localhost:3000/passwordThird?username=",
        jsenc = new nodeRSA(config.publicKey);//可以用来加密的对象
        
    url += jsenc.encrypt(doc.username, 'base64');
    console.log("发送邮件了", doc, url);
    // create reusable transporter object using the default SMTP transport
    let transporter = nodemailer.createTransport({
        host: "smtp.qq.com",
        port: 587,//smtp端口
        secure: false, // true for 465, false for other ports，使用ssl
        auth: {
            user: "2050986448@qq.com", // generated ethereal user
            pass: "sfzrwpsrscoefcfj" // generated ethereal password，qq邮箱的授权码
        }
    });
    
    // console.log("testAccount.user", testAccount.user, testAccount.pass );//这个是内置的用户和授权码
    let info = await transporter.sendMail({//发送邮件
        from: "2050986448@qq.com", // sender address
        to: doc.account, // 接收邮件的人，可以是列表，用逗号分开？
        subject: "航程忘记密码", // Subject line标题
        text: "航程忘记密码链接", // plain text body
        html: "<b>请点击以下链接完成密码重置</b><p>" + url + "</p><p>若以上链接不能正常点击请复制该链接到浏览器直接访问</p>" // html body
    }, function(error, response){
        if(error){//发送邮件出错
            console.log(error);
            res.json({
                success: false,
                description: "发送忘记密码邮件出错"
            })
        }else{//发送邮件成功
            console.log("发送的忘记密码邮件内容" + response.message, response);
            res.json({
                success: true,
                description: "发送了邮件",
                data:{
                    state: 0
                }
            })
        }
        smtpTransport.close(); // 如果没用，关闭连接池,不知道要不要关，暂时好像不用关
    });
}

module.exports={
    sendEmail:function(req, res, next){
        //先检测邮箱在数据库是否存在
        let body = JSON.parse(req.body.data);
        userModel.find({account: body.account}, (err, data)=>{
            if(err){
                res.json({
                    success: false,
                    description:"忘记密码查询用户信息出错"
                })
            }else{
                if(data.length){//邮箱存在
                    sendMail(req, res, next, data[0]).catch(console.error);
                }else{//邮箱不存在
                    res.json({
                        success: true,
                        data:{
                            state: 1
                        }
                    })
                }
            }
        })
    },
    passwordSecond: function(req, res, next){
        let body = JSON.parse(req.body.data),
            rsa = new nodeRSA(config.privateKey);

        body.password = rsa.decrypt(body.password, "utf8");//解密
        body.username = rsa.decrypt(body.username, "utf8");//解密
        userModel.findOneAndUpdate({username: body.username}, {password: body.password}, (err, data)=>{
            if(err){
                console.error(err);
                res.json({
                    success: false,
                    description:"修改密码失败0"
                })
            }else{
                if(data){
                    res.json({
                        success: true,
                        description:"修改密码成功"
                    })
                }else{
                    res.json({
                        success: false,
                        description:"修改密码失败1"
                    })
                }
            }
        })
    }
}